import sqlite3
import spidev
import time

def read_adc(ch):
    #读取mcp3008的某个通道ch
    if ch > 7 or ch < 0:
        return -1
    r = spi.xfer2([1,8 + ch << 4,0])
    data = ((r[1] & 3) << 8) + r[2]
    return data

if __name__ == '__main__':
    print('open adc.db...')
    conn = sqlite3.connect('db/adc2.db')
    try:
        spi = spidev.SpiDev()
        print('open spi device...')
        spi.open(0,0)
        spi.max_speed_hz = 30500#15200
        print('start')
        ls = [0.]*8
        while True:
            t = time.time()
            for i in range(0,8):
                ls[i] = 0.
            for k in range(0,16):
                for i in range(0,8):
                    temp = read_adc(i)
                    ls[i] += temp
            conn.execute('insert into adc (time,t0,t1,t2,t3,t4,t5,t6,t7) values (%d,%f,%f,%f,%f,%f,%f,%f,%f)'%
                         (int(t),ls[0]/32.,ls[1]/32.,ls[2]/32.,ls[3]/32.,ls[4]/32.,ls[5]/32.,ls[6]/32.,ls[7]/32.))
            #time.sleep(0.2)
            conn.commit()
            #print('commit %s,%f'%(str(ls),time.time()-t))
            time.sleep(60.)
    except Exception as e:
        print(e)
        conn.close()
